package com.tvsinfo.jdk.demo.case4_stream;

import com.tvsinfo.jdk.demo.case2_function_interface.dto.Car;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 *规约
 */
public class Stream2_reduce implements Stream_Create_List {

    /**
     * 三、规约
     */
    public void reduce() {
        List<Long> list = Arrays.asList(1L, 2L, 10L, 6L, 8L, 456L, 123L, 45L, 84L, 632L, 14L);

        //实例（流）1、Optional<T> reduce(BinaryOperator<T> accumulator)
        BinaryOperator<Long> binaryOperator = (o, o2) -> o * o2;
        Optional<Long> optionalInteger = list.stream().reduce(binaryOperator);
        optionalInteger.ifPresent(System.out::println);

        //收集器
        Optional<Long> optionalInteger2 = list.stream().collect(Collectors.reducing(binaryOperator));
        optionalInteger.ifPresent(System.out::println);
        System.out.println("------------");


        //实例2、T reduce(T identity, BinaryOperator<T> accumulator)
        Long sum = list.stream().reduce(0L, Long::sum);
        Long sumL = list.stream().reduce(2L, Long::sum);
        System.out.println("实例2 sum:" + sum + ":" + sumL);


        //实例3、reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner)
        List<Object> list2 = Arrays.asList("1", 2, "4", "6");
        String sum3 = list2.stream().reduce("10", (aLong, aLong2) -> aLong + aLong2, (s, s2) -> s + "/+++++" + s2);
        System.out.println("实例3 sum:" + sum3);

        List<Car> cars = getList();
        Integer sum4 = cars.stream().reduce(100, (sum1, car) -> sum1 + car.getPrice(), Integer::compareTo);
        System.out.println("sum4:" + sum4);


        //实例4
        System.out.println("总值(流)：" + cars.stream().mapToInt(Car::getPrice).sum());
        System.out.println("总值(收集器)：" + cars.stream().collect(Collectors.summingInt(Car::getPrice)));
        System.out.println("平均值：" + cars.stream().collect(Collectors.averagingInt(Car::getPrice)));
        System.out.println("拼接：" + cars.stream().map(Car::getBrand).collect(Collectors.joining(",")));
    }
}
